import React, { useState, useRef, useEffect } from 'react';
import type { ChangeEvent } from 'react';
import { Input, Button, message, Spin } from 'antd';
import chatAPI from '../api/chat';
import { EmotionAnalysis } from './EmotionAnalysis';
import './AIChat.css';

interface Message {
  id: string;
  content: string;
  sender: 'user' | 'ai';
  timestamp: Date;
  emotionAnalysis?: Record<string, number>;
}

export const AIChat: React.FC = () => {
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputValue, setInputValue] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [sessionId, setSessionId] = useState<string | undefined>(undefined);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const [currentResponse, setCurrentResponse] = useState('');

  useEffect(() => {
    scrollToBottom();
  }, [messages, currentResponse]);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  const handleSendMessage = async () => {
    if (!inputValue.trim()) return;

    const userMessage: Message = {
      id: Date.now().toString(),
      content: inputValue,
      sender: 'user',
      timestamp: new Date()
    };

    setMessages(prev => [...prev, userMessage]);
    setInputValue('');
    setIsLoading(true);
    setCurrentResponse('');

    try {
      const response = await chatAPI.sendMessage({
        messages: [{
          role: 'user',
          content: inputValue
        }],
        sessionId,
        stream: true
      }, (chunk: string) => {
        setCurrentResponse(prev => prev + chunk);
      });

      setSessionId(response.session_id);
      
      const aiMessage: Message = {
        id: Date.now().toString(),
        content: response.response,
        sender: 'ai',
        timestamp: new Date(),
        emotionAnalysis: response.emotion_analysis
      };

      setMessages(prev => [...prev, aiMessage]);
      setCurrentResponse('');
    } catch (error) {
      console.error('发送消息失败:', error);
      message.error('发送消息失败，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="chat-container">
      <div className="messages-container">
        {messages.map((msg) => (
          <div
            key={msg.id}
            className={`message ${msg.sender === 'user' ? 'user-message' : 'ai-message'}`}
          >
            <div className="message-content">{msg.content}</div>
            {msg.emotionAnalysis && (
              <EmotionAnalysis emotions={msg.emotionAnalysis} />
            )}
          </div>
        ))}
        {currentResponse && (
          <div className="message ai-message">
            <div className="message-content">{currentResponse}</div>
          </div>
        )}
        {isLoading && !currentResponse && (
          <div className="message ai-message">
            <Spin size="small" />
          </div>
        )}
        <div ref={messagesEndRef} />
      </div>
      <div className="input-container">
        <Input
          value={inputValue}
          onChange={(e: ChangeEvent<HTMLInputElement>) => setInputValue(e.target.value)}
          onPressEnter={handleSendMessage}
          placeholder="输入消息..."
          disabled={isLoading}
        />
        <Button
          type="primary"
          onClick={handleSendMessage}
          loading={isLoading}
        >
          发送
        </Button>
      </div>
    </div>
  );
}; 